﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Http;
using Minio.DataModel;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.LexicalAnalysis;

namespace Simple.Services.System
{
    public class utilService
    {
        public static string updateId(string id)
        {
            if (id == null)
            {
                DateTime currentTime = DateTime.Now;
                long timestamp = ((DateTimeOffset)currentTime).ToUnixTimeSeconds();
                string timestampString = timestamp.ToString();
                id = timestampString;
            }
            return id;
        }

        public static async Task<string> GetFileSuffixAsync(string fileName)
        {
            return await Task.Run(() =>
            {
                string suffix = Path.GetExtension(fileName);
                return suffix;
            });
        }
        public static async Task<List<FileMessage>> UploadFilesAsync(string folderPath,List<FileUploadItem> files, string fold, IQhseFileService fileService)
        {
            DateTime dateTime = DateTime.Now;
            List<FileMessage> messages = new List<FileMessage>();
            List<string> names = new List<string>();
            foreach (var file in files)
            {
                string fileName = file.Name;
                byte[] fileBytes = Convert.FromBase64String(file.Base64Content);
                string argumentName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + await utilService.GetFileSuffixAsync(fileName);
                string fileSize = Math.Round((decimal)fileBytes.Length / 1024, 2) + "k";
                Console.WriteLine(fileSize);
                try
                {
                    // 创建一个 IFormFile 对象
                    IFormFile formFile = new FormFile(new MemoryStream(fileBytes), 0, fileBytes.Length,fileName,fileName);
                    Console.WriteLine(formFile.Length);
                    // 使用 IQhseFileService 接口进行文件上传到指定的文件夹
                    await fileService.PutAsync("ssew1",folderPath+"-"+argumentName+"+"+fold, formFile);
                    names.Add(folderPath + "-" + argumentName + "+" + fold);

                    messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功", dateTime));
                }
                catch (Exception e)
                {
                    messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败，失败原因：" + e.ToString(), dateTime));
                }

            }
            string result = string.Join(", ", names);
            messages.Add(FileMessage.CreateNew(result, result, result, 1, "文件上传成功", dateTime));
            return messages;
        }



        public static async Task<FileMessage> UploadFilesAsync(FileUploadItem file, string name, IQhseFileService fileService)
        {
            DateTime dateTime = DateTime.Now;
            string folderPath = "STANDARD";
            FileMessage message = new FileMessage();

            if (string.IsNullOrEmpty(file.Base64Content))
            {
                message.FileStatus = 0;
                return message;
            }

            string fileName = file.Name;
            byte[] fileBytes = Convert.FromBase64String(file.Base64Content);
            string argumentName = name + ".pdf";
            string fileSize = Math.Round((decimal)fileBytes.Length / 1024, 2) + "k";

            try
            {
                // 创建一个 IFormFile 对象
                IFormFile formFile = new FormFile(new MemoryStream(fileBytes), 0, fileBytes.Length, "name", fileName);

                // 使用 IQhseFileService 接口进行文件上传到指定的文件夹
                await fileService.PutPDFAsync("ssew", folderPath+argumentName, formFile);

                // 文件上传成功的逻辑
                message = FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功", dateTime);
            }
            catch (Exception e)
            {
                // 文件上传失败的逻辑
                message = FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败，失败原因：" + e.ToString(), dateTime);
            }

            return message;
        }



        public static async Task<List<FileUploadItem>> GetFilesAsync(string path, IQhseFileService fileService)
        {
            List<string> namesList = path.Split(", ")
                                     .Select(name => name.Trim())  // 去除每个名字前后的空格
                                     .ToList();
            var fileItems = new List<FileUploadItem>();

            foreach (string filePath in namesList)
            {

                try
                {
                    // 使用 IQhseFileService 接口获取文件内容
                    MemoryStream stream = new MemoryStream();
                    await fileService.GetAsync(stream, "ssew", filePath);

                    // 将文件内容转换为 base64
                    byte[] fileBytes = stream.ToArray();
                    string base64Content = Convert.ToBase64String(fileBytes);

                    fileItems.Add(new FileUploadItem { Name = filePath, Base64Content = base64Content });
                }
                catch (Exception e)
                {
                    // 处理获取文件失败的逻辑
                    Console.WriteLine($"获取文件 {filePath} 失败，失败原因：{e}");
                }
            }

            return fileItems;
        }


        public static async Task<List<FileMessage>> UploadFilesAsync(List<FileUploadItem> files, string userId, string foldName, IQhseFileService fileService)
        {
            DateTime dateTime = DateTime.Now;
            string path = Path.Combine(foldName, dateTime.ToString("yyyy-MM-dd-HH-mm-ss") + "+" + userId);

            List<FileMessage> messages = new List<FileMessage>();

            foreach (var file in files)
            {
                string fileName = file.Name;
                byte[] fileBytes = Convert.FromBase64String(file.Base64Content);
                string argumentName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + await utilService.GetFileSuffixAsync(fileName);
                string fileSize = Math.Round((decimal)fileBytes.Length / 1024, 2) + "k";
                string filePath = Path.Combine(path, argumentName);

                try
                {
                    // 创建一个 IFormFile 对象
                    IFormFile formFile = new FormFile(new MemoryStream(fileBytes), 0, fileBytes.Length, "name", fileName);

                    // 使用 IQhseFileService 接口进行文件上传
                    await fileService.PutAsync("ssew", argumentName, formFile);

                    // 文件上传成功的逻辑
                    messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功", dateTime));
                }
                catch (Exception e)
                {
                    // 文件上传失败的逻辑
                    messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败，失败原因：" + e.ToString(), dateTime));
                }
            }

            return messages;
        }


        public static async Task<FileUtilModel> ProcessFiles(List<FileUploadItem> files, string currentPicPath, string userId, string folderName, IQhseFileService fileService)
        {
            var result = new FileUtilModel();
            if (files.Count == 0)
            {
                if (!string.IsNullOrEmpty(currentPicPath))
                {
                    string picPath = Path.Combine(folderName, currentPicPath);
                    // 删除文件夹
                    await fileService.RemoveAsync("ssew", picPath);
                }
                return null;
            }

            var fileUploadItems = files.Select(file => new FileUploadItem
            {
                Name = file.Name,
                Base64Content = file.Base64Content
            }).ToList();
            var hashList = new List<string>(); // 用于存储每个文件的哈希值

            foreach (var file in files)
            {
                using (var sha256 = SHA256.Create())
                {
                    byte[] byteArray = Convert.FromBase64String(file.Base64Content);
                    byte[] hash = sha256.ComputeHash(byteArray);
                    string hashString = BitConverter.ToString(hash).Replace("-", "").ToLower();
                    hashList.Add(hashString);
                }
            }
            var msgs = await UploadFilesAsync(fileUploadItems, userId, folderName,fileService);
            bool uploadSuccess = msgs.All(msg => msg.FileStatus == 1);
            if (uploadSuccess)
            {
                if (!string.IsNullOrEmpty(currentPicPath))
                {
                    string picPath = Path.Combine(folderName, currentPicPath);
                    // 删除文件夹
                    await fileService.RemoveAsync("ssew", picPath);
                }
                result.Pic = msgs.FirstOrDefault()?.dateTime.ToString("yyyy-MM-dd-HH-mm-ss") + "+" + userId + "/";
                result.hash = hashList;
                return result;
            }

            return null;
        }

        public static bool isEmpty(ComDangerPageInputModel input)
        {
            if (string.IsNullOrEmpty(input.DangerOrganizationName) &&
                string.IsNullOrEmpty(input.CheckOrganizationName) &&
                string.IsNullOrEmpty(input.DangerCategory) &&
                (input.WorkSpecialty == null || input.WorkSpecialty.Count == 0) &&
                (input.WorkType == null || input.WorkType.Count == 0) &&
                (input.WorkRisk == null || input.WorkRisk.Count == 0) &&
                (input.Location == null || input.Location.Count == 0) &&
                (input.CheckTypes == null || input.CheckTypes.Count == 0) &&
                (input.DangerType == null || input.DangerType.Count == 0) &&
                (input.Status == null || input.Status.Count == 0) &&
                input.TimeOn == null && input.TimeEnd == null &&
                string.IsNullOrEmpty(input.UserName) && (input.EnterSys == null || input.EnterSys.Count == 0) &&
                string.IsNullOrEmpty(input.ErpNo))
            {
                return true;
            }

            return false;
        }

        public static bool isAnyNotEmpty(ComViolationPageInputModel input)
        {
            // 检查属性是否有一个不为空
            if (!string.IsNullOrEmpty(input.OrganizationName) ||
                input.TimeOn != null ||
                input.TimeEnd != null ||
                !string.IsNullOrEmpty(input.UserName) ||
                input.CheckTypes.Count > 0 ||
                !string.IsNullOrEmpty(input.CheckOrganizationName) ||
                input.WorkSpecialty.Count > 0 ||
                input.WorkType.Count > 0 ||
                input.WorkRisk.Count > 0 ||
                input.Location.Count > 0 ||
                input.Position.Count > 0 ||
                input.Age.Count > 0 ||
                input.WorkYears.Count > 0 ||
                input.ViolationType.Count > 0 ||
                input.EmployeeType.Count > 0 ||
                !string.IsNullOrEmpty(input.ViolationCategory) ||
                !string.IsNullOrEmpty(input.ScoreSymbol) ||
                input.Score != null ||
                !string.IsNullOrEmpty(input.FineSymbol) ||
                input.Fine != null ||
                input.UserId != null ||  input.EnterSys.Count > 0)
            {
                return false;
            }

            return true;
        }

        // 计算指定日期所属的 ISO 8601 周数
        public static int GetIso8601WeekOfYear(DateTime date)
        {
            // 将日期转换为指定日历的实例
            Calendar calendar = CultureInfo.InvariantCulture.Calendar;

            // 获取指定日期的周几
            DayOfWeek dayOfWeek = calendar.GetDayOfWeek(date);

            // 如果日期是一年的最后几天且该周的大部分日期在下一年，则将其视为下一年的第一周
            if (dayOfWeek >= DayOfWeek.Monday && (7 - (int)dayOfWeek) < 3)
            {
                date = date.AddDays(7);
            }

            // 获取指定日期所属的年份
            int year = calendar.GetYear(date);

            // 计算指定日期所属的 ISO 8601 周数
            int week = calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

            // 考虑跨年的情况
            if (week >= 52 && date.Month == 1)
            {
                year--;
            }

            return week;
        }

        // 获取指定年份的 ISO 8601 总周数
        public static int GetIso8601WeeksInYear(int year)
        {
            // 创建一个指定年份的日期
            DateTime date = new DateTime(year, 12, 31);

            // 计算指定年份的 ISO 8601 周数
            int weeksInYear = GetIso8601WeekOfYear(date);

            return weeksInYear;
        }

        public static async void PushDanger(DangerMsg latestDanger)
        {
            string push = "http://10.132.6.133:8082/api/qhse/messagepush/Message/Push";
            PushModel pushModel = new PushModel();
            var year = latestDanger.Time.Value.Year;
            var month = latestDanger.Time.Value.Month;
            var day = latestDanger.Time.Value.Day;
            var date = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"); // 使用统一的时间格式化方法
            pushModel.msg = $"您好，在{year}年{month}月{day}日，发生一个【{latestDanger.Type}】，请点击查看详情。";
            Console.WriteLine(latestDanger.Id);
            if (latestDanger.Type == "一般隐患")
            {
                pushModel.url = $"http://10.132.6.46:8082/api/SSO/SSO#/hazardQuery?id={latestDanger.Id}";
                pushModel.pushType = PushType.Third;
                pushModel.orgId = latestDanger.OrgId;
            }
            else if (latestDanger.Type == "一般操作违章" || latestDanger.Type == "一般管理违章")
            {
                pushModel.url = $"http://10.132.6.46:8082/api/SSO/SSO#/violationQuery?id={latestDanger.Id}";
                pushModel.pushType = PushType.Third;
                pushModel.orgId = latestDanger.OrgId;
            }
            else if (latestDanger.Type == "较大隐患" || latestDanger.Type == "重大隐患")
            {
                pushModel.url = $"http://10.132.6.46:8082/api/SSO/SSO#/hazardQuery?id={latestDanger.Id}";
                pushModel.pushType = PushType.All;
                pushModel.orgId = latestDanger.OrgId;
            }else if(latestDanger.Type == "严重操作违章" || latestDanger.Type == "严重管理违章"
                || latestDanger.Type == "重大操作违章" || latestDanger.Type == "重大管理违章")
            {
                pushModel.url = $"http://10.132.6.46:8082/api/SSO/SSO#/violationQuery?id={latestDanger.Id}";
                pushModel.pushType = PushType.All;
                pushModel.orgId = latestDanger.OrgId;
            }

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("PushToken", "L8xJuJUOZvGj0znHBgwiRqi1aJmWC0ywEiwqinE9+NBn5NbSfgcaW7hDv5JSK9x5cClkI27XYE4S73XJcCdD35an5tq48R32lVVLn6aEwc8hDqw534nYMA/eeWjzrNPH46Z3LOTU5yPSIahb12Lttk1AyQ3iP8");

                    // 序列化推送模型为 JSON 字符串，并构建 HttpContent
                    HttpContent content = new StringContent(JsonConvert.SerializeObject(pushModel), Encoding.UTF8, "application/json");

                    // 发送 POST 请求
                    var response = await client.PostAsync(push, content);

                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(json);
                    }
                    else
                    {
                        // 处理HTTP请求失败的情况
                        Console.WriteLine($"请求失败，状态码: {response.StatusCode}");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                // HttpClient 发生的异常
                Console.WriteLine($"HttpClient 请求发生异常: {ex.Message}");
            }
            catch (Exception ex)
            {
                // 其他异常
                Console.WriteLine($"发生异常: {ex.Message}");
            }
        }

    }

}

